package com.yuyou.fn.educational.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yuyou.fn.common.service.ISiteConfigService;
import com.yuyou.fn.common.util.MD5Helper;
import com.yuyou.fn.common.util.OkHttpClientUtils;
import com.yuyou.fn.common.util.SignatureUtil;
import com.yuyou.fn.educational.service.IDataCenterStudentService;
import com.yuyou.fn.educational.vo.DataCenterStudent;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class DataCenterStudentServiceImpl implements IDataCenterStudentService {

    private static final Logger log  = LoggerFactory.getLogger(DataCenterStudentServiceImpl.class) ;
    private OkHttpClient client = OkHttpClientUtils.getIgnoreSsLClient(30, 500);

    @Resource
    private ISiteConfigService siteConfigService;

    @Override
    public boolean insertStudent(DataCenterStudent dataCenterStudent) {

        Request request = getRequest("%s/sc-api/rest/api/student/add.do?appId=%s&appKey=%s&ts=%s&signature=%s", JSONObject.toJSONString(dataCenterStudent));
        Response response = null ;
        try {
            response = client.newCall(request).execute();

            if(!response.isSuccessful()){
                log.error("[请求失败] http code={}" ,response.code());
                return false ;
            }

            String result = response.body().string();
            JSONObject resultJson = JSONObject.parseObject(result);
            int code = resultJson.getInteger("code");
            //新增成功或记录已经存在
            if (code == 200 || resultJson.getString("msg").indexOf("记录已存在") != -1) {
                String cid = resultJson.getString("object");
                dataCenterStudent.setCid(cid);
                return true ;
            } else {
                log.warn("[数据中心返回异常]{}",result);
            }
        } catch (Exception e) {
            log.error("[请求失败] studentId={} " , dataCenterStudent.getBizClientId() , e);
        }finally {
            if(response != null ){
                response.close();
            }
        }
        return false;
    }

    @Override
    public boolean updateStudent(DataCenterStudent dataCenterStudent) {

        Request request = getRequest("%s/sc-api/rest/api/student/update.do?appId=%s&appKey=%s&ts=%s&signature=%s", JSONObject.toJSONString(dataCenterStudent));
        Response response = null ;
        try {
            response = client.newCall(request).execute();
            if(!response.isSuccessful()){
                log.error("[请求失败] http code={}" ,response.code());
                return false ;
            }
            String result = response.body().string();
            JSONObject resultJson = JSONObject.parseObject(result);
            int code = resultJson.getInteger("code");
            if (code != 200) {
                log.warn("[数据中心返回异常]{}",result);
                return false ;
            }else{
                return true ;
            }
        } catch (Exception e) {
            log.error("[请求失败] studentId={}" ,dataCenterStudent.getBizClientId() , e);
        }finally {
            if(response != null ){
                response.close();
            }
        }
        return false ;
    }

    @Override
    public boolean changeOrNew(DataCenterStudent dataCenterStudent) {
        Request request = getRequest("%s/sc-api/rest/api/student/changeOrNew2.do?appId=%s&appKey=%s&ts=%s&signature=%s", JSONObject.toJSONString(dataCenterStudent));
        Response response = null ;
        try {
            response = client.newCall(request).execute();
            if(!response.isSuccessful()){
                log.error("[请求失败] http code={}" ,response.code());
                return false ;
            }
            String result = response.body().string();
            JSONObject resultJson = JSONObject.parseObject(result);
            int code = resultJson.getInteger("code");
            if (code != 200) {
                log.warn("[数据中心返回异常]{}",result);
                return false ;
            }else{
                return true ;
            }
        } catch (Exception e) {
            log.error("[请求失败] studentId={}" ,dataCenterStudent.getBizClientId() , e);
        }finally {
            if(response != null ){
                response.close();
            }
        }
        return false ;
    }

    public Request getRequest(String urlPattern, String bodyJson) {
        String baseUrl = siteConfigService.getConfigValueFromCache("data_cener_domain");
        String appId = siteConfigService.getConfigValueFromCache("data_center_appid");
        String appKey = MD5Helper.MD5(siteConfigService.getConfigValueFromCache("data_center_appkey"));
        Long ts = System.currentTimeMillis();
        String salt = SignatureUtil.generateSalt(16);
        String signature = SignatureUtil.generateRemoteSignature(salt,SignatureUtil.generateLocalSignature(null, appId, appKey, ts, salt));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), bodyJson);
        Request request = new Request.Builder().url( String.format( urlPattern, baseUrl , appId, appKey,ts , signature ) ).post(requestBody).build();
        return request;
    }
}
